/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2017-11-09 13:14:31
 * @Description: 
 */

(function() {

    var util = {};

    util.cloneObj = function(objA, objB) {
        for (var i in objA) {
            objB[i] = objA[i];
        }
        return objB;
    };

    util.unix_to_datetime = function(unix) {
        if (unix == '') return '';
        var unix = parseInt(unix / 1000),
            now = new Date(parseInt(unix) * 1000);
        return now.Format('yyyy-MM-dd hh:mm:ss');
    };

    util.subString = function(str, length) {
        str = (str.length > length) ? str.substring(0, length) + '...' : str;
        return str;
    };

    util.lightString = function(arr, str, color) {
        var pattern = '(' + arr.join("|") + ')';
        var reg = new RegExp(pattern, "g");
        str = str.replace(reg, "<span style='color:" + color + "'>$1</span>");
        return str;
    };

    util.replaceSpace = function(str) {
        str = util.HTMLEnCode(str);
        str = str.replace(/ {4,}/g, "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + str;
    };

    util.HTMLEnCode = function(s) {
        if (s.length == 0) {
            return "";
        }
        /*  
        s = str.replace(/&/g,"&gt;");  
        s = s.replace(/</g,"&lt;");  
        s = s.replace(/>/g,"&gt;");  
        s = s.replace(/ /g,"&nbsp;");  
        s = s.replace(/\'/g,"'");  
        s = s.replace(/\"/g,"&quot;");
        */
        s = s.replace(/\n/g, "<br>");
        s = s.replace(/\r/g, "<br>");
        return s;
    };

    util.HTMLDeCode = function(s) {
        if (s.length == 0) {
            return "";
        }
        /* 
        s = str.replace(/&gt;/g,"&");  
        s = s.replace(/&lt;/g,"<");  
        s = s.replace(/&gt;/g,">");  
        s = s.replace(/&nbsp;/g," ");  
        s = s.replace(/'/g,"\'");  
        s = s.replace(/&quot;/g,"\"");
        */
        s = s.replace(/<br>/g, "\n");
        s = s.replace(/<br>/g, "\r");
        return s;
    };

    util.HTMLAllEnCode = function(s) {
        if (s.length == 0) {
            return "";
        }
        // s = str.replace(/&/g, "&gt;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "'");
        s = s.replace(/\"/g, "&quot;");
        s = s.replace(/\r\n/g, "<br>");
        s = s.replace(/\n/g, "<br>");
        s = s.replace(/\r/g, "<br>");
        return s;
    };

    util.HTMLAllbrCode = function(s) {
        if (s) {
            var reg = new RegExp("\\n", "g");
            if (s.length == 0) {
                return "";
            }
            s = s.replace(reg, "<br>");
            return s;
        } else {
            return '';
        }
    };

    util.HTMLAllDeCode = function(s) {
        if (s.length == 0) {
            return "";
        }
        // s = str.replace(/&gt;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/'/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        s = s.replace(/<br>/g, "\n");
        s = s.replace(/<br>/g, "\r");
        return s;
    };

    util.voliHtml = function(s) {
        if (s.length == 0) {
            return "";
        }
        s = s.replace(/<(\S*?)[^>]*>|.*?<\/\\1>|<.*?\/>/g, '');
        return s;
    };

    Date.prototype.Format = function(fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //日 
            "h+": this.getHours(), //小时 
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds(), //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };

    util.safariDate = function(timeStr) {
        return timeStr.substr(0, 10) + "T" + timeStr.substr(11, 8);
    };

    util.getCurrentDate = function(num) {
        var time,
            myDate = new Date();
        if (typeof(num) == 'undefined') {
            time = myDate.Format("yyyy-MM-dd");
        } else if (num == 'all') {
            time = myDate.Format("yyyy-MM-dd hh:mm:ss");
        } else {
            myDate = new Date((myDate) - num * 24 * 3600 * 1000);
            time = myDate.Format("yyyy-MM-dd");
        }
        return time;
    };

    util.lastNumDay = function(num) {
        var today = new Date();
        var lastTime = today.getTime() - 1000 * 60 * 60 * 24 * num;
        return new Date(lastTime);
    };

    util.lastNumMonth = function(num, date) {
        var h_month, h_day, h_year, c_month, c_dayc_year, max_h_day;
        if (date) {
            c_month = date.getMonth();
        } else {
            date = util.lastNumDay(1);
            c_month = date.getMonth() + 1;
        }
        c_day = date.getDate();
        c_year = date.getFullYear();

        if ((c_month - num) > 0) {
            h_month = c_month - num;
            h_year = c_year;
        } else {
            h_month = (c_month + Math.ceil(num / 12) * 12) - num;
            h_year = c_year - Math.ceil(num / 12);
        }

        max_h_day = new Date(h_year, h_month, 0).getDate();

        if (c_day < max_h_day) {
            h_day = c_day;
        } else {
            h_day = max_h_day;
        }
        return util.FormatDate(h_year, h_month, h_day);
    };

    util.isEmail = function(email) {
        var bool = false,
            filter = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (filter.test(email)) {
            bool = true;
        }
        return bool;
    };

    util.isLength = function(str, min, max) {
        var bool = true,
            len = str.length;
        if (len < min || len > max) {
            bool = false;
        }
        return bool;
    };

    //异常处理预埋管理统一接口 
    util.logError = function(obj) {
        console.log(obj);
        //业务逻辑 
    };

    util.queryString = function(item) {
        var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
        return svalue ? svalue[1] : svalue;
    };

    util.tip = function(str, dom, time) {
        var html = $("<div class='tip'><span>" + str + "</span></div>");

        if ($(dom).find('.tip').length < 1) {
            dom.append(html);
        }

        if (time > 0) {
            setTimeout(function() {
                html.remove();
            }, time);
        }
    };

    util.domainURI = function(str) {
        var durl = /(http:\/\/)([^\/]+)\//i;
        var domain = str.match(durl);
        return domain; //arr
    }

    util.domainStr = function() {
        var host = window.location.host;
        var arr = host.split('.'),
            length = arr.length,
            rootDomain = arr[length - 2].replace(/(\w)/, function(v) {
                return v.toUpperCase()
            }) + '.' + arr[length - 1];
        return rootDomain;
    }

    util.rootDomain = function(domain) {
        var arr = domain.split('.'),
            length = arr.length,
            rootDomain = arr[length - 2] + '.' + arr[length - 1];
        return rootDomain;
    };

    /**
    *    var obj = {
       expires : 1, 
       path:'/',
       //domain:'',
    };
    */
    util.setCookie = function(name, value, options) {

        if (options.expires) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (options.expires * 24 * 60 * 60 * 1000));
        }

        //encodeURI方法的作用是进行编码，主要防治value中有特殊字符  
        var str = name + '=' + encodeURI(value) + (expires ? '; expires=' + expires.toGMTString() : '') + (options.path ? '; path=' + options.path : '/') + (options.domain ? '; domain=' + options.domain : '');
        //+ (options.secure ? '; secure' : '');
        //+ (options.httpOnly ? '; HttpOnly' : '');
        //console.log(str);
        document.cookie = str;
    };

    util.getCookie = function(name) {
        var search = name + "=",
            offset, end;
        if (document.cookie.length > 0) {
            offset = document.cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = document.cookie.indexOf(";", offset);
                if (end == -1) {
                    end = document.cookie.length;
                };
                return decodeURI(document.cookie.substring(offset, end));
            }
        }
        return "";
    };

    util.delCookie = function(name, obj) {
        util.setCookie(name, "", obj);
    };

    util.device = function() {
        var u = navigator.userAgent,
            name;
        if (u.indexOf('Windows Phone') > -1) {
            name = 'windowsPhone';
        } else if (u.indexOf('iPhone') > -1) {
            name = 'iPhone';
        } else if (u.indexOf('iPad') > -1) {
            name = 'iPad';
        } else if (u.indexOf('Android') > -1) {
            name = 'android';
        }
        return name;
    };

    util.deviceSize = function() {
        var bool = true,
            width = $(window).width();
        if (width > 640) {
            bool = false;
        }
        return bool;
    };

    util.FormatDate = function(Year, Month, Day) {
        var CurrentDate = Year + "-";
        if (Month >= 10) {
            CurrentDate += Month + "-";
        } else {
            CurrentDate += "0" + Month + "-";
        }
        if (Day >= 10) {
            CurrentDate += Day;
        } else {
            CurrentDate += "0" + Day;
        }
        return CurrentDate;
    };

    util.getMonthDayDate = function(str) {
        var arr = new Date(parseInt(str) * 1000).toString().split(' ');
        return arr[1] + ' ' + arr[2];
    };

    util.cutString = function(str, len) {
        if (str.length * 2 <= len) {
            return str;
        }
        var strlen = 0;
        var s = "";
        for (var i = 0; i < str.length; i++) {
            s = s + str.charAt(i);
            if (str.charCodeAt(i) > 128) {
                strlen = strlen + 2;
                if (strlen >= len) {
                    return s.substring(0, s.length - 1) + "...";
                }
            } else {
                strlen = strlen + 1;
                if (strlen >= len) {
                    return s.substring(0, s.length - 2) + "...";
                }
            }
        }
        return s;
    };

    if (typeof define === "function") {
        define(function(require, exports, module) {
            module.exports = util;
        });
    }

})();